<template>
  <div class="questionnaire-fill-container">
    <div class="page-header">
      <h2>填写问卷</h2>
      <div class="header-actions">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
      </div>
    </div>

    <div class="fill-content" v-loading="loading">
      <el-card v-if="questionnaireData">
        <div class="questionnaire-header">
          <h1 class="questionnaire-title">{{ questionnaireData.title }}</h1>
          <p class="questionnaire-description">{{ questionnaireData.description }}</p>
          
          <el-alert
            v-if="eventInfo"
            :title="`活动：${eventInfo.title}`"
            type="info"
            :closable="false"
            class="event-info"
          >
            <template #default>
              <p>活动时间：{{ eventInfo.startTime }} ~ {{ eventInfo.endTime }}</p>
              <p>活动地点：{{ eventInfo.location }}</p>
            </template>
          </el-alert>
        </div>

        <div class="form-container">
          <questionnaire-form
            v-model="answers"
            :questions="questionnaireData.questions"
            @answer-change="handleAnswerChange"
          />
        </div>

        <div class="submit-container">
          <el-button
            type="primary"
            size="large"
            @click="handleSubmit"
            :loading="submitting"
            :disabled="submitted"
          >
            {{ submitted ? '已提交' : '提交问卷' }}
          </el-button>
        </div>
      </el-card>

      <el-empty
        v-else-if="!loading"
        description="未找到问卷信息或问卷已关闭"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'
import { getEventQuestionnaire, getFrontEventQuestionnaire } from '@/api/questionnaire'
import { getEventDetail } from '@/api/event'
import { getFrontEventDetail } from '@/api/frontEvent'
import { submitQuestionnaireAnswers, submitFrontQuestionnaireAnswers } from '@/api/questionnaire'
import QuestionnaireForm from './components/QuestionnaireForm.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 获取参数
const eventId = computed(() => route.params.eventId)
const questionnaireId = computed(() => route.query.id)
const userId = computed(() => userStore.userId)

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const submitted = ref(false)
const questionnaireData = ref(null)
const eventInfo = ref(null)
const answers = ref([])

// 初始化
onMounted(async () => {
  if (!eventId.value) {
    ElMessage.error('缺少活动ID参数')
    goBack()
    return
  }

  await fetchEventInfo()
  await fetchQuestionnaire()
})

// 获取活动信息
const fetchEventInfo = async () => {
  try {
    loading.value = true
    // 使用前台活动详情API
    const res = await getFrontEventDetail(eventId.value)
    if (res.code === 200 && res.data) {
      eventInfo.value = res.data
    } else {
      ElMessage.error('获取活动信息失败')
      goBack()
    }
  } catch (error) {
    console.error('获取活动信息出错:', error)
    ElMessage.error('获取活动信息失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 获取问卷信息
const fetchQuestionnaire = async () => {
  try {
    loading.value = true
    // 如果URL中提供了问卷ID，直接使用此问卷
    if (questionnaireId.value) {
      console.log('使用从URL获取的问卷ID:', questionnaireId.value);
      // 使用现有的问卷数据，由于问卷数据已经从ticket-detail中获取并传递过来
      // 此处可以根据需要调用获取问卷详情的API
      
      // 如果已经收到前端传来的数据，直接使用
      if (route.query.data) {
        try {
          const parsedData = JSON.parse(decodeURIComponent(route.query.data));
          questionnaireData.value = parsedData;
          initAnswers();
          return;
        } catch (e) {
          console.error('解析问卷数据失败:', e);
        }
      }
      
      // 使用前台API获取问卷数据
      const res = await getFrontEventQuestionnaire(eventId.value);
      if (res.code === 200 && res.data) {
        questionnaireData.value = res.data;
        initAnswers();
      } else {
        ElMessage.warning(res.msg || '该活动暂无问卷');
        goBack();
      }
    } else {
      // 无问卷ID时也使用前台API
      const res = await getFrontEventQuestionnaire(eventId.value);
      if (res.code === 200 && res.data) {
        questionnaireData.value = res.data;
        initAnswers();
      } else {
        ElMessage.warning(res.msg || '该活动暂无问卷');
        goBack();
      }
    }
  } catch (error) {
    console.error('获取问卷信息出错:', error);
    ElMessage.error('获取问卷信息失败');
    goBack();
  } finally {
    loading.value = false;
  }
}

// 初始化答案数组
const initAnswers = () => {
  if (questionnaireData.value && questionnaireData.value.questions && questionnaireData.value.questions.length > 0) {
    answers.value = new Array(questionnaireData.value.questions.length).fill(null).map(
      (_, i) => questionnaireData.value.questions[i].questionType === 'multiple' ? [] : null
    );
  }
}

// 处理答案变化
const handleAnswerChange = (data) => {
  console.log('答案变化:', data)
}

// 处理提交
const handleSubmit = async () => {
  if (!questionnaireData.value || !questionnaireData.value.questions) return
  
  // 验证必填项
  const emptyRequiredIndex = questionnaireData.value.questions.findIndex((q, idx) => {
    if (!q.isRequired) return false

    const answer = answers.value[idx]
    if (q.questionType === 'single' || q.questionType === 'text') {
      return !answer
    } else if (q.questionType === 'multiple') {
      return !answer || answer.length === 0
    }
    return false
  })

  if (emptyRequiredIndex !== -1) {
    ElMessage.warning(`第 ${emptyRequiredIndex + 1} 题是必填项，请填写完整`)
    return
  }

  // 格式化答案为API所需格式
  const formattedAnswers = {}
  questionnaireData.value.questions.forEach((question, index) => {
    formattedAnswers[question.id || index + 1] = answers.value[index]
  })

  try {
    submitting.value = true
    const submitData = {
      eventId: eventId.value,
      answers: formattedAnswers
    }

    // 使用前台API提交问卷答案
    const res = await submitFrontQuestionnaireAnswers(submitData)
    if (res.code === 200) {
      ElMessage.success('问卷提交成功，感谢您的参与！')
      submitted.value = true
      
      // 提交成功后等待一会儿再返回
      setTimeout(() => {
        goBack()
      }, 2000)
    } else {
      ElMessage.error(res.msg || '问卷提交失败')
    }
  } catch (error) {
    console.error('提交问卷出错:', error)
    ElMessage.error('问卷提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const goBack = () => {
  // 如果是从票券详情页过来，返回票券详情页
  if (route.query.from === 'ticket-detail') {
    router.push(`/front/user/ticket-detail?id=${route.query.ticketId || ''}`);
  } 
  // 否则尝试返回活动详情
  else {
    // 前台活动详情页
    router.push(`/front/event/detail/${eventId.value}`);
  }
}
</script>

<style scoped>
.questionnaire-fill-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.fill-content {
  margin-bottom: 20px;
}

.questionnaire-header {
  padding: 10px 0 20px 0;
  border-bottom: 1px dashed #ddd;
  margin-bottom: 20px;
}

.questionnaire-title {
  font-size: 24px;
  text-align: center;
  margin-bottom: 12px;
  color: var(--text-primary);
}

.questionnaire-description {
  font-size: 14px;
  text-align: center;
  color: var(--text-secondary);
  margin-bottom: 20px;
}

.event-info {
  margin: 20px 0;
}

.form-container {
  margin: 20px 0;
}

.submit-container {
  text-align: center;
  padding: 20px 0;
  border-top: 1px dashed #ddd;
  margin-top: 20px;
}
</style> 